<?php

namespace app\controllers\merchant\shop;

use app\models\admin\app\AppAccessModel;
use app\models\merchant\system\BargainModel;
use app\models\merchant\system\OperationRecordModel;
use app\models\shop\GoodsModel;
use app\models\shop\GroupOrderModel;
use app\models\shop\SaleGoodsModel;
use app\models\shop\SaleGoodsStockModel;
use Yii;
use yii\web\MerchantController;
use app\models\shop\ShopBargainInfoModel;
use app\models\shop\StockModel;

class BargainsController extends MerchantController
{

    public $enableCsrfValidation = false; //禁用CSRF令牌验证，可以在基类中设置

    public function actionList()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $model = new ShopBargainInfoModel();
            $params['key'] = $params['key'];
            $params['merchant_id'] = yii::$app->session['uid'];
            $params['is_promoter'] = 1;
            $arr = $model->do_select($params);
            if ($arr['status'] == 200) {
                $res = array();
                for ($i = 0; $i < count($arr['data']); $i++) {

                    $array['data'] = $arr['data'][$i];
                    $appModel = new AppAccessModel();
                    $app = $appModel->find(['`key`' => $params['key']]);


                    $goodsModel = new GoodsModel();

                    $goods = $goodsModel->find(['id' => $array['data']['goods_id']]);

                    $stockModel = new StockModel();

                    $stock = $stockModel->find(['id' => $array['data']['stock_id']]);


                    $sql = "select count(id) as num from shop_order where merchant_id = {$params['merchant_id']} and `key`  ='{$params['key']}'";
                    $num = $stockModel->querySql($sql);

                    $sql = "select avatar  from shop_user where id = {$array['data']['promoter_user_id']}";
                    $avatar = $stockModel->querySql($sql);


                    $bargin = $model->do_one(['orderby' => 'id desc', 'goods_id' => $array['data']['goods_id']]);
                    //$model = new ShopBargainInfoModel();
                    unset($data);
                    $model1 = new ShopBargainInfoModel();
                    $data['field'] = "avatar,nickname,price,shop_bargain_info.create_time";
                    $data['join'][] = ['inner join', 'shop_user', 'shop_user.id=shop_bargain_info.user_id'];
                    $data['is_promoter'] = 0;
                    $data['goods_id'] = $array['data']['goods_id'];
                    $data['shop_bargain_info.merchant_id'] = $array['data']['merchant_id'];
                    $data['shop_bargain_info.key'] = $array['data']['key'];
                    $list = $model1->do_select($data);

                    //$res[$i]['app_name'] = $app['data']['name'];
                    $res[$i]['avatar'] = $avatar[0]['avatar'];
                    //   $res[$i]['bargain_poster'] = $app['data']['bargain_poster'];
                    $res[$i]['goods_name'] = $goods['data']['name'];
                    $res[$i]['pic_url'] = $stock['data']['pic_url'];
                    $res[$i]['number'] = $goods['data']['fictitious_help_bargain'] + $num[0]['num'];
                    $res[$i]['price'] = $bargin['data']['goods_price'];
                    $res[$i]['min_pirce'] = $goods['data']['bargain_price'];
                    $res[$i]['cost_price'] = $array['data']['goods_price'];
                    $res[$i]['end_time'] = $array['data']['end_time'];
                    $res[$i]['format_create_time'] = $array['data']['format_create_time'];
                    if ($list['status'] == 200) {
                        $res[$i]['bargin'] = $list['data'];
                    } else {
                        $res[$i]['bargin'] = array();
                    }

                }
                return result(200, '请求成功', $res);
            } else {
                return $arr;
            }

        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionGoods()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $goodsModel = new SaleGoodsModel();
            $goods = $goodsModel->do_select(['key' => $params['key'], 'merchant_id' => yii::$app->session['uid'], 'is_bargain' => 0, 'is_flash_sale' => 0, 'is_recruits' => 0, 'is_open_assemble' => 0, 'supplier_id' => 0, 'status' => 1]);
            return $goods;
        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionSingle($id)
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $goodsModel = new SaleGoodsModel();
            $goods = $goodsModel->do_one(['key' => $params['key'], 'merchant_id' => yii::$app->session['uid'], 'id' => $id]);
            if($goods['status']==200){
                $goods['data']['bargain_rule']  = json_decode($goods['data']['bargain_rule'],true);
                $goods['data']['format_bargain_start_time'] =date('Y-m-d H:i:s', $goods['data']['bargain_start_time']);
                $goods['data']['format_bargain_end_time'] =date('Y-m-d H:i:s', $goods['data']['bargain_end_time']);
            }
            return $goods;
        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionUpdate($id)
    {
        //添加砍价活动开启记录
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $goodsModel = new SaleGoodsModel();
            $must = ['key', 'is_bargain'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $bargainModel = new BargainModel();
            if(isset($params['is_bargain'])){
                if($params['is_bargain']==1){
                    $bargainData = array(
                        'key' => $params['key'],
                        'merchant_id' => yii::$app->session['uid'],
                        'goods_id' => $id,
                        'is_bargain' => $params['is_bargain'] ?? 0,
                        'bargain_start_time' => $params['bargain_start_time'] ? strtotime($params['bargain_start_time']) : 0,
                        'bargain_end_time' => $params['bargain_end_time'] ? strtotime($params['bargain_end_time']) : 0,
                        'is_buy_alone' => $params['is_buy_alone'] ?? 0,
                        'fictitious_initiate_bargain' => $params['fictitious_initiate_bargain'] ?? 0,
                        'fictitious_help_bargain' => $params['fictitious_help_bargain'] ?? 0,
                        'bargain_price' => $params['bargain_price'] ?? 0,
                        'help_number' => $params['help_number'] ?? 0,
                        'bargain_limit_time' => $params['bargain_limit_time'] ?? 0,
                        'bargain_rule' => $params['bargain_rule'] ? json_encode($params['bargain_rule']) : '',
                    );
                    $transaction = yii::$app->db->beginTransaction();
                    try {
                        $array = $bargainModel->do_delete(['goods_id' => $id, 'key' => $params['key']]);
                        $res =  $bargainModel->do_add($bargainData);
                        if($res['status']!=200){
                            $transaction->rollBack(); //
                        }
                        $params['bargain_start_time'] = isset($params['bargain_start_time']) ? strtotime($params['bargain_start_time']) : 0;
                        $params['bargain_end_time'] = isset($params['bargain_end_time']) ? strtotime($params['bargain_end_time']) : 0;
                        $params['bargain_limit_time'] = isset($params['bargain_limit_time']) ? $params['bargain_limit_time'] : 0;
                        $params['bargain_rule'] = $params['bargain_rule'] ? json_encode($params['bargain_rule']) : '';
                        $array = $goodsModel->do_update(['id' => $id, 'key' => $params['key']], $params);
                        if($array['status']!=200){
                            $transaction->rollBack(); //
                        }
                        $transaction->commit(); //只有执行了commit(),对于上面数据库的操作才会真正执行
                    } catch (Exception $e) {
                        $transaction->rollBack(); //回滚
                        return result(500, "新增失败");
                    }
                }else{
                    $array = $goodsModel->do_update(['id' => $id, 'key' => $params['key']], ['is_bargain'=>0]);
                    $array = $bargainModel->do_delete(['goods_id' => $id, 'key' => $params['key']]);
                }
                if ($array['status'] == 200){
                    //添加操作记录
                    $operationRecordModel = new OperationRecordModel();
                    $operationRecordData['key'] = $params['key'];
                    $operationRecordData['merchant_id'] = yii::$app->session['uid'];
                    $operationRecordData['operation_type'] = '更新';
                    $operationRecordData['operation_id'] = $id;
                    $operationRecordData['module_name'] = '砍价';
                    $operationRecordModel->do_add($operationRecordData);
                }
                return $array;

            }
        } else {
            return result(500, "请求方式错误");
        }

    }

//    public function actionOrder()
//    {
//        if (yii::$app->request->isGet) {
//            $request = yii::$app->request; //获取 request 对象
//            $params = $request->get(); //获取地址栏参数
//
//            $orderModel = new GroupOrderModel();
//            $orders  = $orderModel->do_select(['key'=>$params['key'],'merchant_id'=>yii::$app->session['uid'],'is_bargain'=>1]);
//
//            return $orders;
//        } else {
//            return result(500, "请求方式错误");
//        }
//
//    }

}